const { pool } = require('../config/db');
const { success, error } = require('../utils/response');
const moment = require('moment');

// 归还图书
exports.returnBook = async (req, res, next) => {
  try {
    const { borrowId, condition = 'good', notes } = req.body;
    const userId = req.userId;

    // 获取借阅记录
    const [records] = await pool.query(`
      SELECT
        br.*,
        b.name as book_name,
        b.stock
      FROM borrow_records br
      LEFT JOIN books b ON br.book_id = b.id
      WHERE br.id = ? AND br.user_id = ? AND br.status = 'borrowed'
    `, [borrowId, userId]);

    if (records.length === 0) {
      return error(res, '借阅记录不存在或已归还', 404);
    }

    const record = records[0];

    // 计算逾期天数和罚款
    const now = moment();
    const dueDate = moment(record.due_date);
    const isOverdue = now.isAfter(dueDate);
    const overdueDays = isOverdue ? now.diff(dueDate, 'days') : 0;
    const finePerDay = parseFloat(process.env.FINE_PER_DAY) || 1.00;
    const fineAmount = overdueDays * finePerDay;

    // 开始事务
    const connection = await pool.getConnection();
    await connection.beginTransaction();

    try {
      // 更新借阅记录
      await connection.query(
        'UPDATE borrow_records SET status = "returned", return_date = NOW() WHERE id = ?',
        [borrowId]
      );

      // 增加图书库存
      await connection.query(
        'UPDATE books SET stock = stock + 1 WHERE id = ?',
        [record.book_id]
      );

      // 创建归还记录
      await connection.query(
        'INSERT INTO return_records (borrow_record_id, user_id, book_id, condition, fine_amount, notes) VALUES (?, ?, ?, ?, ?, ?)',
        [borrowId, userId, record.book_id, condition, fineAmount, notes]
      );

      // 如果有逾期，创建逾期记录
      if (isOverdue && fineAmount > 0) {
        await connection.query(
          'INSERT INTO overdue_records (borrow_record_id, user_id, book_id, overdue_days, fine_amount) VALUES (?, ?, ?, ?, ?)',
          [borrowId, userId, record.book_id, overdueDays, fineAmount]
        );
      }

      await connection.commit();

      // 归还成功后，异步通知预约用户
      const { notifyNextReservation } = require('./reservationController');
      setTimeout(() => {
        notifyNextReservation(record.book_id);
      }, 100);

      success(res, {
        fineAmount: fineAmount,
        overdueDays: overdueDays,
        condition: condition,
        returnDate: moment().format('YYYY-MM-DD HH:mm:ss')
      }, '归还成功');

    } catch (err) {
      await connection.rollback();
      throw err;
    } finally {
      connection.release();
    }

  } catch (err) {
    next(err);
  }
};

// 获取用户的归还记录
exports.getReturnRecords = async (req, res, next) => {
  try {
    const userId = req.userId;
    const { page = 1, limit = 10 } = req.query;

    const offset = (page - 1) * limit;

    const [records] = await pool.query(`
      SELECT
        rr.id,
        rr.return_date,
        rr.condition,
        rr.fine_amount,
        rr.notes,
        b.id as book_id,
        b.name as book_name,
        b.author,
        b.cover,
        br.borrow_date,
        br.due_date
      FROM return_records rr
      LEFT JOIN books b ON rr.book_id = b.id
      LEFT JOIN borrow_records br ON rr.borrow_record_id = br.id
      WHERE rr.user_id = ?
      ORDER BY rr.return_date DESC
      LIMIT ? OFFSET ?
    `, [userId, parseInt(limit), offset]);

    // 获取总数
    const [total] = await pool.query(
      'SELECT COUNT(*) as count FROM return_records WHERE user_id = ?',
      [userId]
    );

    success(res, {
      records,
      pagination: {
        current: parseInt(page),
        limit: parseInt(limit),
        total: total[0].count,
        pages: Math.ceil(total[0].count / limit)
      }
    });
  } catch (err) {
    next(err);
  }
};

// 获取逾期记录
exports.getOverdueRecords = async (req, res, next) => {
  try {
    const userId = req.userId;

    const [records] = await pool.query(`
      SELECT
        o.id,
        o.overdue_days,
        o.fine_amount,
        o.status,
        o.created_date,
        b.id as book_id,
        b.name as book_name,
        b.author,
        br.borrow_date,
        br.due_date
      FROM overdue_records o
      LEFT JOIN books b ON o.book_id = b.id
      LEFT JOIN borrow_records br ON o.borrow_record_id = br.id
      WHERE o.user_id = ?
      ORDER BY o.created_date DESC
    `, [userId]);

    success(res, records);
  } catch (err) {
    next(err);
  }
};

// 支付罚款
exports.payFine = async (req, res, next) => {
  try {
    const { overdueId } = req.body;
    const userId = req.userId;

    // 获取逾期记录
    const [overdueRecords] = await pool.query(
      'SELECT * FROM overdue_records WHERE id = ? AND user_id = ? AND status = "unpaid"',
      [overdueId, userId]
    );

    if (overdueRecords.length === 0) {
      return error(res, '逾期记录不存在或已支付', 404);
    }

    // 更新支付状态
    await pool.query(
      'UPDATE overdue_records SET status = "paid" WHERE id = ?',
      [overdueId]
    );

    success(res, {
      overdueId: overdueId,
      fineAmount: overdueRecords[0].fine_amount,
      payTime: moment().format('YYYY-MM-DD HH:mm:ss')
    }, '罚款支付成功');

  } catch (err) {
    next(err);
  }
};
